package cn.itcast.mq.config;

import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.amqp.support.converter.Jackson2JsonMessageConverter;
import org.springframework.amqp.support.converter.MessageConverter;
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

/**
 * @author Xiao
 * @version 1.0
 * @description 生产者消息确认
 * @date 2021/11/19
 */
@Slf4j
@Configuration
public class CommonConfig implements ApplicationContextAware {
    /**
     * 定义Return回调
     * @param context
     * @throws BeansException
     */
    @Override
    public void setApplicationContext(ApplicationContext context) throws BeansException {
        // 获取RabbitTemplate
        RabbitTemplate rabbitTemplate = context.getBean(RabbitTemplate.class);
        // 设置ReturnCallback--》消息发送到交换机但是没有放入队列时触发
        rabbitTemplate.setReturnCallback((message, replyCode, replyText, exchange, routingKey) -> {
            // 投递失败，记录日志
            log.info("消息发送失败，消息：{}，应答码：{}，原因：{}，交换机：{}，路由键：{}",
                    message, replyCode, replyText, exchange, routingKey);
            // 如果有业务需要，可以重发消息
            System.err.println("消息未达到队列，重发消息。。。");
        });
    }
}
